package com.situ.onlinebookstore.front.controller.api;

import com.situ.onlinebookstore.common.entity.Addr;
import com.situ.onlinebookstore.common.vo.Result;
import com.situ.onlinebookstore.common.entity.User;
import com.situ.onlinebookstore.front.service.AddrService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api/user/addr")
@RequiredArgsConstructor
public class AddrApiController {
    private final AddrService addrService;

    //添加 post请求 以JSON传递数据
    @PostMapping
    public Result add(@RequestBody Addr addr, HttpSession session){
        User user = (User) session.getAttribute("user");
        addr.setUserId(user.getId());
        try {
            addrService.add(addr);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
    //修改 put请求 以JSON传递数据
    @PutMapping
    public Result edit(@RequestBody Addr addr, HttpSession session){
        User user = (User) session.getAttribute("user");
        addr.setUserId(user.getId());
        try {
            addrService.edit(addr);
            return Result.ok();
        }catch (Exception e){
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
//删除 delete请求 以form-data传递数据
@DeleteMapping
public Result remove(@RequestBody Addr addr, HttpSession session){
    User user = (User) session.getAttribute("user");
    addr.setUserId(user.getId());
    try {
        addrService.remove(addr);
        return Result.ok();
    }catch (Exception e){
        e.printStackTrace();
        return Result.error(e.getMessage());
    }
}

//根据ID查询 get请求，路径参数传递id
    @GetMapping("/{id}")
    public Result get(@PathVariable Integer id){
        return Result.ok(addrService.getById(id));
    }

    @GetMapping
    public Result get(HttpSession session){
        User user = (User)session.getAttribute("user");
        return Result.ok(addrService.getByUserId(user.getId()));
    }
}
